package com.anxin.controller;

import com.anxin.annotation.LoginRequire;
import com.anxin.annotation.RoleRequired;
import com.anxin.common.PageResult;
import com.anxin.common.Result;
import com.anxin.entity.SysUser;
import com.anxin.security.util.SecurityUtils;
import com.anxin.service.SysUserService;
import com.anxin.system.dto.RegisterDTO;
import com.anxin.system.dto.UserInfoDTO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;

import java.util.List;

@Tag(name = "系统用户管理")
@RestController
@RequestMapping("/api/user")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SecurityUtils securityUtils;

    @Operation(summary = "根据ID获取用户")
    @GetMapping("/{id}")
    @LoginRequire
    public Result<SysUser> getById(@Parameter(description = "用户ID") @PathVariable String id) {
        return Result.success(userService.getById(id));
    }

    @Operation(summary = "分页查询用户列表")
    @GetMapping("/page")
    @RoleRequired("ADMIN") // 限制只有 ADMIN 角色才能访问
    @LoginRequire
    public Result<PageResult<SysUser>> page(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "真实姓名") @RequestParam(required = false) String realName,
            @Parameter(description = "手机号") @RequestParam(required = false) String phone,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status
    ) {
        Page<SysUser> page = userService.page(pageNum, pageSize, username, realName, phone, status);
        return Result.page(page);
    }

    @Operation(summary = "保存或更新用户")
    @PostMapping("/save")
    @LoginRequire
    public Result<Boolean> save(@RequestBody SysUser user) {
        return Result.success(userService.saveOrUpdate(user));
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    @LoginRequire
    public Result<Boolean> delete(@PathVariable String id) {
        return Result.success(userService.removeById(id));
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/info")
    @LoginRequire
    public Result<UserInfoDTO> getUserInfo() {
        UserInfoDTO userInfo = securityUtils.getCurrentUserInfo();
        SysUser user = userService.getById(userInfo.getUserId());
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(userInfo);
    }

    @Operation(summary = "保存当前登录用户个人信息")
    @PostMapping("/info")
    @LoginRequire
    public Result<Boolean> saveUserInfo(@RequestBody SysUser user) {
        UserInfoDTO userInfo = securityUtils.getCurrentUserInfo();
        // 只允许修改自己的信息
        if (!userInfo.getUserId().equals(user.getId())) {
            return Result.error("无权修改他人信息");
        }
        boolean ok = userService.updateById(user);
        return ok ? Result.success(true) : Result.error("保存失败");
    }

    @Operation(summary = "用户列表")
    @GetMapping("/list")
    @RoleRequired("ADMIN") // 限制只有 ADMIN 角色才能访问
    @LoginRequire
    public Result<List<SysUser>> getAllUsers() {
        return Result.success(userService.getAllUsers());
    }

    @Operation(summary = "管理员-添加用户")
    @PostMapping("/add")
    @RoleRequired("ADMIN")
    @LoginRequire
    public Result<Boolean> addUser(@RequestBody SysUser user) {
        UserInfoDTO userInfo = securityUtils.getCurrentUserInfo();
        if (!userInfo.getRoleId().equals("ADMIN")) {
            return Result.error("无权添加用户");
        }
        if (userService.findByUsername(user.getUsername()) != null) {
            return Result.error("用户已存在");
        }

        // 将 SysUser 转换为 RegisterDTO
        RegisterDTO registerDTO = new RegisterDTO();
        registerDTO.setUsername(user.getUsername());
        registerDTO.setPassword(user.getPassword());
        registerDTO.setRealName(user.getRealName());
        registerDTO.setPhone(user.getPhone());
        registerDTO.setEmail(user.getEmail());
        userService.register(registerDTO);
        return Result.success(true);
    }

    @Operation(summary = "管理员-修改用户")
    @PostMapping("/update")
    public Result<Boolean> updateUser(@RequestBody SysUser user) {
        // 获取当前登录用户信息
        securityUtils.getCurrentUserInfo();
        return Result.success(userService.updateById(user));
    }
}
